package com.fdb.smcts.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ResourceBundle;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpUtil {
	private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

	/** FTP操作对象*/
	//public static FTPClient ftpClient;
	/** 登录用户名*/
	private static String name;
	/** 登录密码*/
	private static String password;
	/** 登录IP地址*/
	private static String host;
	/** 登录端口*/
	private static int port;
	/**下载到本地服务器的文件路径*/
	private static String localDownloadPath;
	/**生成本服务器文件的文件路径*/
	private static String localUploadPath;
	 /**远程上传ftp的文件路径*/
	private static String remoteUploadPath;
	 /**远程下载ftp的文件路径*/
	private static String remoteDownloadPath;
	/** 编码*/
	private static String code ="GBK";
	
	private volatile static boolean isInit=false;
	
	
	
	private static void init() throws Exception {
		//获取配置文件
		try {
			ResourceBundle res = ResourceBundle.getBundle("ftp");
			host = res.getString("ftp.host");
			port =  Integer.valueOf(res.getString("ftp.port"));
			name = res.getString("ftp.username");
			password = res.getString("ftp.pwd");
			localDownloadPath =  res.getString("ftp.localDownloadPath");
			localUploadPath =  res.getString("ftp.localUploadPath");
			remoteUploadPath =  res.getString("ftp.remoteUploadPath");
			remoteDownloadPath =  res.getString("ftp.remoteDownloadPath");
		}catch(Exception e) {
			logger.error("获取ftp配置信息出错！",e);
			throw new Exception("获取ftp配置信息出错！"+e);
		}
		isInit=true;
	}
	
	/**
	 * 文件下载
	 * 
	 * @param fileName 要下载的文件名 
	 * @return true表示成功，否则返回错误信息
	 * @throws Exception 
	 * @throws IOException 
	 * @throws SocketException 
	 */
	
	public static boolean downLoadFile(String fileName) throws Exception  {
		if(!isInit) {
			init();
		}
		
		FTPClient ftpClient = null;
		boolean result = false;
		OutputStream ous = null;
		logger.info("downLoadFile 开始下载："+fileName+"文件");
		try {
			if(ftpClient == null || !ftpClient.isAvailable()) {
				ftpClient = new FTPClient();
				if(!connect(ftpClient)) {
					logger.info("链接ftp出错！");
					return false;
				}
			}
			ftpClient.changeWorkingDirectory(remoteDownloadPath);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] files = ftpClient.listFiles(fileName);
			if (files.length == 0)
				throw new IOException(fileName + "文件不存在");
			else {
				ous = new FileOutputStream(new File(localDownloadPath+fileName));
				 /** 写入本地文件*/
				result = ftpClient.retrieveFile(fileName, ous);
			}
			return result;
		}catch(Exception e) {
			logger.error("文件下载出错！",e);
			throw new Exception("文件下载出错！"+e);
		}finally{
			if (ous != null) {
				ous.close();
			    ous = null;
			}
            if (ftpClient != null) {
                ftpClient.disconnect();
            }
		}
	}
		
	/**
	 * ftp文件上传
	 * @param fileName 当前文件名称
	 * @return true表示成功，否则返回错误信息
	 */
	public static boolean uploadFile(String fileName) throws Exception{
		logger.info("uploadFile 开始上传："+fileName+"文件");
		if(!isInit) {
			init();
		}
		
		FTPClient ftpClient = null;
		boolean result = false;
		InputStream ins = null;
		try {
			if(ftpClient == null || !ftpClient.isAvailable()) {
				ftpClient = new FTPClient();
				if(!connect(ftpClient)) {
					logger.info("链接ftp出错！");
					return false;
				}
			}
			logger.info("开始上传"+fileName);
			ins = new FileInputStream(localUploadPath+fileName);
			ftpClient.changeWorkingDirectory(remoteUploadPath);
			result = ftpClient.storeFile(fileName, ins);
			logger.info("上传结束");
		} catch (IOException e) {
			logger.error("上传文件失败",e);
			throw new Exception("上传文件失败！:"+e);
		}finally{
			if (ins != null) {
				ins.close();
				ins = null;
			}
			if (ftpClient != null) {
                ftpClient.disconnect();
            }
		}
		return result;
	}

	/**
	 * 检查目标文件是否存在
	 * @param fileName :要检查的文件
	 * @throws Exception 
	 */
	public static boolean isFileExists(String fileName) throws Exception {
		if(!isInit) {
			init();
		}
		
		FTPClient ftpClient = null;
		try {
			if (ftpClient == null || !ftpClient.isAvailable()) {
				ftpClient = new FTPClient();
				if(!connect(ftpClient)) {
					logger.info("链接ftp出错！");
					return false;
				}
			}
			ftpClient.changeWorkingDirectory(remoteUploadPath);
			ftpClient.enterLocalPassiveMode();
			logger.info("开始文件读取:"+fileName);
			FTPFile[] files = ftpClient.listFiles(fileName);
			if (files.length == 0) {
				logger.info(fileName+"文件不存在");
			} else {
				logger.info(fileName+"文件存在");
				return true;
			}
		} catch (IOException e) {
			logger.error("检查文件文件是否存在出错！"+e);
			throw new Exception("检查文件文件是否存在出错"+e);
		}finally{
			if (ftpClient != null) {
                ftpClient.disconnect();
            }
		}
		return false;
	}
	/**
	 * 连接FTP服务器
	 * @throws SocketException
	 * @throws IOException
	 */
	public static boolean connect(FTPClient ftpClient) throws SocketException, IOException {
		boolean result = false;
		ftpClient.connect(host, port);
		ftpClient.setControlEncoding(code);
		// 判断是否完成握手，以便输入用户密码
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			if (ftpClient.login(name, password)) {
				result = true;
			}
		}else {
			ftpClient.logout();
			if (ftpClient.isConnected()) {
				ftpClient.disconnect();
			}
		}
		return result;
	}
	
	public static void main(String[] args) throws Exception {
		uploadFile("123.txt");
	}
}
